package cn.regexp.elasticjob.controller;


import cn.regexp.elasticjob.config.Job;
import cn.regexp.elasticjob.domain.SysJob;
import cn.regexp.elasticjob.mapper.JobMapper;
import cn.regexp.elasticjob.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态任务添加
 * 
 * <p>可以用于同一个任务，需要不同的时间来进行触发场景<p>
 * 
 * @author zyf
 * 
 * @Date 2022/4/22
 *
 */
@RestController
public class JobController {
	
	@Autowired
	private JobService jobService;
	@Autowired
	private JobMapper jobMapper;

	/**
	 * 获取正在运行的定时任务
	 * @return
	 */
	@GetMapping("/runList")
	public List<SysJob> getRunningJob() {
		return jobMapper.getRuningJob();
	}
	
	/**
	 * 注册动态任务（适用于脚本逻辑已存在的情况，只是动态添加了触发的时间）
	 * @param jobId	任务id
	 * @return
	 */
	@GetMapping("job/register")
	public Object registerJob(long jobId) {
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("status", true);
		//获取数据库中的数据
		SysJob sysJob = jobMapper.getById(jobId);
		if (sysJob.getJobStatus()==1) {
			result.put("status", false);
			result.put("message", "已启动的无需再次启动");
			return result;
		}
		//封装数据
		Job job =jobService.pakageJob(sysJob);
		if (!StringUtils.hasText(job.getJobName())) {
			result.put("status", false);
			result.put("message", "name not null");
			return result;
		}
		
		if (!StringUtils.hasText(job.getCron())) {
			result.put("status", false);
			result.put("message", "cron not null");
			return result;
		}
		
		if (!StringUtils.hasText(job.getJobType())) {
			result.put("status", false);
			result.put("message", "getJobType not null");
			return result;
		}
		
		if ("SCRIPT".equals(job.getJobType())) {
			if (!StringUtils.hasText(job.getScriptCommandLine())) {
				result.put("status", false);
				result.put("message", "scriptCommandLine not null");
				return result;
			}
		} else {
			if (!StringUtils.hasText(job.getJobClass())) {
				result.put("status", false);
				result.put("message", "jobClass not null");
				return result;
			}
		}
		try {
			//将任务注册到zookeeper
			jobService.registerJob(job,false);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("status", false);
			result.put("message", e.getMessage());
		}
		return result;
	}

	/**
	 * 启动定时任务
	 * @param jobId	任务名称
	 * @throws Exception
	 */
	@GetMapping("/job/start")
	public Object startJob(long jobId) {
		SysJob sysJob = jobMapper.getById(jobId);
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("status", true);
		try {
			jobService.startJob(sysJob.getJobName());
		} catch (Exception e) {
			result.put("status", false);
			result.put("message", e.getMessage());
		}
		//修改定时任务的状态
		jobMapper.updateStatusById(jobId,1);
		return result;
	}

	/**
	 * 触发定时任务
	 * @param jobId	任务名称
	 * @throws Exception
	 */
	@GetMapping("/job/trigger")
	public Object triggerJob(long jobId) {
		SysJob sysJob = jobMapper.getById(jobId);
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("status", false);
		result.put("message","未启动的定时任务无法触发！");
		if (sysJob.getJobStatus()==1){
			try {
				jobService.triggerJob(sysJob.getJobName());
				result.put("status", true);
				result.put("message","success");
				return result;
			} catch (Exception e) {
				result.put("message", e.getMessage());
			}
		}

		return result;
	}
	
	/**
	 * 删除动态注册的任务
	 * @param jobId	任务名称
	 * @throws Exception
	 */
	@GetMapping("/job/remove")
	public Object removeJob(long jobId) {
		SysJob sysJob = jobMapper.getById(jobId);
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("status", true);
		try {
			jobService.removeJob(sysJob.getJobName());
		} catch (Exception e) {
			result.put("status", false);
			result.put("message", e.getMessage());
		}
		jobMapper.updateStatusById(jobId,0);
		return result;
	}
	/**
	 * 暂停动态注册的任务（
	 * @param jobId	任务名称
	 * @throws Exception
	 */
	@GetMapping("/job/stop")
	public Object stopJob(long jobId) {
		SysJob sysJob = jobMapper.getById(jobId);
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("status", true);
		try {
			jobService.stopJob(sysJob.getJobName());
		} catch (Exception e) {
			result.put("status", false);
			result.put("message", e.getMessage());
		}
		jobMapper.updateStatusById(jobId,2);
		return result;
	}
	/**
	 * 重新启动动态注册的任务（
	 * @param jobId	任务名称
	 * @throws Exception
	 */
	@GetMapping("/job/recover")
	public Object recoverJob(long jobId) {
		SysJob sysJob = jobMapper.getById(jobId);
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("status", true);
		try {
			jobService.recoverJob(sysJob.getJobName());
		} catch (Exception e) {
			result.put("status", false);
			result.put("message", e.getMessage());
		}
		jobMapper.updateStatusById(jobId,1);
		return result;
	}

	/**
	 * 获取定时任务的配置信息
	 * @param jobId	任务名称
	 * @throws Exception
	 */
	@GetMapping("/job/getConfig")
	public Object getConfig(long jobId) {
		SysJob sysJob = jobMapper.getById(jobId);
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("status", true);
		try {
			Job config = jobService.getConfig(sysJob.getJobName());
			result.put("result",config);
		} catch (Exception e) {
			result.put("status", false);
			result.put("message", e.getMessage());
		}
	//	jobMapper.updateStatusById(jobId,1);
		return result;
	}

	/**
	 * 更新
	 * @param jobId	任务名称
	 * @throws Exception
	 */
	@GetMapping("/update")
	public Object update(long jobId) {
		SysJob sysJob = jobMapper.getById(jobId);
		sysJob.setCron("0/10 * * * * ?");
		return jobMapper.update(sysJob);
	}

	/**
	 * 更新作业配置.
	 * @param jobId 作业配置
	 * @return 更新后的作业配置
	 */
	@GetMapping("/job/updateConfig")
	public Object updateConfig(long jobId) {
		SysJob sysJob = jobMapper.getById(jobId);
		Map<String, Object> result = new HashMap<String, Object>(2);
		try {
			//封装数据
			Job job = jobService.pakageJob(sysJob);
			job.setScriptCommandLine("cmd echo test2222");
			job.setCron("0/10 * * * * ?");
			//更新配置
			jobService.updateConfig(job);
			//	result.put("result",config);
		} catch (Exception e) {
			result.put("status", false);
			result.put("message", e.getMessage());
		}
		result.put("status", true);
		return result;
	}

	/**
	 * 恢复状态为启用的定时任务
	 * @return 更新后的作业配置
	 */
	@GetMapping("/job/recoverRun")
	public Object recoverRun() {
		List<SysJob> runingJob = jobMapper.getRuningJob();
		Map<String, Object> result = new HashMap<String, Object>(2);
		for (SysJob sysJob : runingJob) {
//			jobService.stopJob(sysJob.getJobName());//将原任务注销
			//封装数据
			Job job = jobService.pakageJob(sysJob);
			//以本地配置启动
			job.setDisabled(true);
			//将定时任务重新注册
			jobService.registerJob(job,true);
		}
		result.put("status", true);
		return result;
	}

}
